package com.jwthhealth_pub.old.physicalfitness.view;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.common.preference.PreferenceKey;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.individual.module.UcenterModule;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.sign.view.SignPwActivity;
import com.jwthhealth_pub.old.signutil.model.db.UserInfoDao;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/1/13.
 */

public class IndividualActivity extends Activity {

    private int REQUEST = 0;
    private int CHANGEPHONEREQUEST = 1;

    @BindView(R.id.sign_topbar)
    TitleLayout signTopbar;
    @BindView(R.id.tv_title_one)
    TextView tvTitleOne;
    @BindView(R.id.iv_info_one)
    ImageView ivInfoOne;
    @BindView(R.id.tv_title_two)
    TextView tvTitleTwo;
    @BindView(R.id.tv_info_two)
    TextView tvInfoTwo;
    @BindView(R.id.tv_info_thi_one)
    TextView tvInfoThiOne;
    @BindView(R.id.tv_info_thi_two)
    TextView tvInfoThiTwo;
    @BindView(R.id.tv_title_thi)
    TextView tvTitleThi;
    @BindView(R.id.tv_title_for)
    TextView tvTitleFor;
    @BindView(R.id.tv_info_for)
    TextView tvInfoFor;
    @BindView(R.id.tv_title_fiv)
    TextView tvTitleFiv;
    @BindView(R.id.tv_info_fiv)
    TextView tvInfoFiv;
    @BindView(R.id.tv_title_six)
    TextView tvTitleSix;
    @BindView(R.id.tv_info_six)
    TextView tvInfoSix;
    @BindView(R.id.tv_title_sev)
    TextView tvTitleSev;
    @BindView(R.id.tv_info_sev)
    TextView tvInfoSev;
    @BindView(R.id.tv_title_eni)
    TextView tvTitleEni;
    @BindView(R.id.tv_info_eni)
    TextView tvInfoEni;
    @BindView(R.id.tv_title_nin)
    TextView tvTitleNin;
    @BindView(R.id.tv_info_nin)
    TextView tvInfoNin;
    @BindView(R.id.tv_title_ten)
    TextView tvTitleTen;
    @BindView(R.id.tv_info_ten)
    TextView tvInfoTen;
    @BindView(R.id.tv_title_ele)
    TextView tvTitleEle;
    @BindView(R.id.tv_info_ele)
    TextView tvInfoEle;
    @BindView(R.id.layout_list)
    LinearLayout layoutList;

    private int[] imgs = new int[]{R.mipmap.portrait_1, R.mipmap.portrait_2, R.mipmap.portrait_3,
            R.mipmap.portrait_4, R.mipmap.portrait_5, R.mipmap.portrait_6,
            R.mipmap.portrait_7, R.mipmap.portrait_8, R.mipmap.portrait_9,
            R.mipmap.portrait_10, R.mipmap.portrait_11, R.mipmap.portrait_12};
    private UserInfoDao userInfoDao;
    private int choiceSex;
    private int year;
    private int month;
    private int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_individual_info);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        initTop();
        inttInfoList();
    }

    private void inttInfoList() {
        //判断登录状态，初始化个人信息
        boolean isLogin = App.preferenceUtil.getBoolean(PreferenceKey.CACHE_TOKEN, false);
        userInfoDao = UserInfoDao.getInstance();
        LoginModel.DataBean userinfoModel = userInfoDao.queryUserinfoModel();

        if (userinfoModel != null) {
            ivInfoOne.setBackgroundResource(imgs[App.preferenceUtil.getInt(PreferenceKey.PORTRAITPOS, 0)]);
        }

        if (isLogin && userinfoModel != null) {
            // TODO: 2017/1/14 加载个人信息
            if (userinfoModel.getPhone() != null && userinfoModel.getPhone().length() > 0) {
                tvInfoThiTwo.setText(userinfoModel.getPhone());
            } else {
                tvInfoThiTwo.setText("未填写");
            }

            if (userinfoModel.getUsername() != null && userinfoModel.getUsername().length() > 0) {
                tvInfoTwo.setText(userinfoModel.getUsername());
            } else {
                tvInfoTwo.setText("未填写");
            }

            if (userinfoModel.getEmail() != null && userinfoModel.getEmail().length() > 0) {
                tvInfoFor.setText(userinfoModel.getEmail());
            } else {
                tvInfoFor.setText(getResources().getString(R.string.individual_title_add));
            }

            if (userinfoModel.getAddress() != null && userinfoModel.getAddress().length() > 0) {
                tvInfoFiv.setText(userinfoModel.getAddress());
            } else {
                tvInfoFiv.setText(getResources().getString(R.string.individual_title_add));
            }


            if (userinfoModel.getSex() != null && userinfoModel.getSex().length() > 0) {
                tvInfoSix.setText(userinfoModel.getSex());
            } else {
                tvInfoSix.setText(getResources().getString(R.string.individual_title_choice));
            }

            if (userinfoModel.getBirthday() != null && userinfoModel.getBirthday().length() > 0) {
                tvInfoSev.setText(userinfoModel.getBirthday());
            } else {
                tvInfoSev.setText(getResources().getString(R.string.individual_title_choice));
            }

            if (userinfoModel.getHeight() != null && userinfoModel.getHeight().length() > 0) {
                tvInfoEni.setText(userinfoModel.getHeight());
            } else {
                tvInfoEni.setText("0CM");
            }

            if (userinfoModel.getWeight() != null && userinfoModel.getWeight().length() > 0) {
                tvInfoNin.setText(userinfoModel.getWeight());
            } else {
                tvInfoNin.setText("0Kg");
            }

        } else {
        }
    }

    private void initTop() {
        signTopbar.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    @OnClick({R.id.iv_info_one, R.id.layout_two, R.id.layout_for, R.id.layout_fiv, R.id.layout_six, R.id.layout_sev, R.id.layout_eni, R.id.layout_nin, R.id.layout_ten, R.id.layout_ele, R.id.tv_info_thi_one})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_info_one:
                //添加头像
                Intent intent = new Intent(this, IndividualHeadPortraitActivity.class);
                startActivityForResult(intent, REQUEST);
                break;
            case R.id.layout_two:
                //修改昵称
                showOptHint(2);
                break;
            case R.id.layout_for:
                //修改邮箱
                showOptHint(4);
                break;
            case R.id.layout_fiv:
                //修改地址
                showOptHint(5);
                Intent intentFiv = new Intent(this, ChoiceAddressActivity.class);
                startActivity(intentFiv);
                break;
            case R.id.layout_six:
                //性别
                showOptHint(6);
                break;
            case R.id.layout_sev:
                //生日
                showOptHint(7);
                break;
            case R.id.layout_eni:
                //身高
                showOptHint(8);
                break;
            case R.id.layout_nin:
                //体重
                showOptHint(9);
                break;
            case R.id.layout_ten:
                showOptHint(10);
                //修改密码
                break;
            case R.id.layout_ele:
                //收获地址
                break;
            case R.id.tv_info_thi_one:
                //修改手机号码
                showOptHint(3);
                break;
            default: break;
        }
    }

    private void showOptHint(int i) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view;
        boolean isBuilderShow = true;
        switch (i) {
            case 2:
                //昵称
                view = View.inflate(this, R.layout.view_dialog_add, null);
                final EditText ed = (EditText) view.findViewById(R.id.et);
                builder.setTitle("添加昵称");
                builder.setView(view);
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (ed.getText() != null && ed.getText().length() > 0) {
                            String un = ed.getText().toString().trim();
                            tvInfoTwo.setText(un);
                            boolean b = userInfoDao.updateUserName(un);
                            LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                            Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "username", un);
                            username.enqueue(new Callback<UcenterModule>() {
                                @Override
                                public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                                    UcenterModule body = response.body();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                            } catch (Exception e) {
                                                Log.d("IndividualActivity", e.toString());
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Call<UcenterModule> call, Throwable t) {

                                }
                            });
                        }
                    }
                });
                break;

            case 3:
                //修改电话
                startActivityForResult(new Intent(this, ChangePhoneNumActivity.class), CHANGEPHONEREQUEST);
                break;

            case 4:
                //修改邮箱
                view = View.inflate(this, R.layout.view_dialog_add, null);
                final EditText emailEd = (EditText) view.findViewById(R.id.et);
                emailEd.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                builder.setTitle("输入邮箱");
                builder.setView(view);
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (emailEd.getText() != null && emailEd.getText().length() > 0) {
                            String phone = emailEd.getText().toString().trim();
                            tvInfoFor.setText(phone);
                            boolean b = userInfoDao.updateUserEmail(phone);

                            LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                            Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "email", phone);
                            username.enqueue(new Callback<UcenterModule>() {
                                @Override
                                public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Call<UcenterModule> call, Throwable t) {

                                }
                            });

                        }
                    }
                });
                break;
            case 6:
                //性别
                builder.setTitle("选择性别");
                //0 man , 1 woman
                choiceSex = 0;
                builder.setSingleChoiceItems(new String[]{"男", "女"}, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d("IndividualActivity", "i:" + i);
                        choiceSex = i;
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        String updateSex = "1";

                        if (choiceSex == 0) {
                            tvInfoSix.setText("男");
                            updateSex = "2";
                        } else if (choiceSex == 1) {
                            tvInfoSix.setText("女");
                            updateSex = "1";
                        } else {
                            Log.d("IndividualActivity", "性别出错");
                        }
                        boolean b = userInfoDao.updateUsersex(choiceSex);

                        LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                        Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "sex", updateSex);
                        username.enqueue(new Callback<UcenterModule>() {
                            @Override
                            public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onFailure(Call<UcenterModule> call, Throwable t) {

                            }
                        });

                    }
                });
                break;
            case 7:
                //生日
                Calendar c = Calendar.getInstance();
                year = c.get(Calendar.YEAR);
                month = c.get(Calendar.MONTH);
                day = c.get(Calendar.DAY_OF_MONTH);
                this.showDialog(0);
                isBuilderShow = false;
                Log.d("IndividualActivity", "year:" + year);
                break;

            case 8:
                //身高
                view = View.inflate(this, R.layout.view_dialog_add, null);
                final EditText heightEd = (EditText) view.findViewById(R.id.et);
                heightEd.setInputType(8194);
                heightEd.setHint("cm");
                builder.setTitle("输入身高");
                builder.setView(view);
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (heightEd.getText() != null && heightEd.getText().length() > 0) {
                            String height = heightEd.getText().toString().trim();
                            int hei = Integer.parseInt(height);
                            if (hei < 0 || hei > 200) {
                                Toast.makeText(IndividualActivity.this, "身高不再有效范围", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            tvInfoEni.setText(height + "cm");
                            boolean b = userInfoDao.updateUserHeight(height);

                            LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                            Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "height", height);
                            username.enqueue(new Callback<UcenterModule>() {
                                @Override
                                public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Call<UcenterModule> call, Throwable t) {

                                }
                            });

                        }
                    }
                });
                break;
            case 9:
                //体重
                view = View.inflate(this, R.layout.view_dialog_add, null);
                final EditText weightEd = (EditText) view.findViewById(R.id.et);
                weightEd.setInputType(8194);
                weightEd.setHint("kg");
                builder.setTitle("输入体重");
                builder.setView(view);
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (weightEd.getText() != null && weightEd.getText().length() > 0) {

                            String weight = weightEd.getText().toString().trim();

                            int wei = Integer.parseInt(weight);
                            if (wei < 0 || wei > 200) {
                                Toast.makeText(IndividualActivity.this, "体重超出范围", Toast.LENGTH_SHORT).show();
                            }

                            tvInfoNin.setText(weight + "kg");
                            boolean b = userInfoDao.updateUserWeight(weight);

                            LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                            Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "weight", weight);
                            username.enqueue(new Callback<UcenterModule>() {
                                @Override
                                public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Call<UcenterModule> call, Throwable t) {

                                }
                            });
                        }
                    }
                });
                break;

            case 10:
                //修改密码
                isBuilderShow = false;
                startActivity(new Intent(this, SignPwActivity.class));
                break;
            default:
                break;
        }

        if (isBuilderShow && i!=3 && i!=5) {
            builder.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST && resultCode == RESULT_OK) {
            int portraintPos = data.getIntExtra(Constant.SELECTEDPOS, 0);
            // TODO: 2017/1/14 更新头像
            ivInfoOne.setBackgroundResource(imgs[portraintPos]);
        } else {

        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == 0) {
            return new DatePickerDialog(this, mOnDateSetListener, year, month, day);
        } else {
            return super.onCreateDialog(id);
        }
    }

    private DatePickerDialog.OnDateSetListener mOnDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    year = year;
                    month = monthOfYear;
                    day = dayOfMonth;
                    StringBuffer data = new StringBuffer()
                            //Month is 0 base so add 1
                            .append(year).append("-")
                            .append(month + 1).append("-")
                            .append(day).append(" ");
                    Log.d("IndividualActivity", "date:" + data);

                    tvInfoSev.setText(data);

                    LoginModel.DataBean dataBean = userInfoDao.queryUserinfoModel();
                    Call<UcenterModule> username = ApiHelper.ucenter(dataBean.getId(), dataBean.getAndroidtoken(), "birthday", String.valueOf(data));
                    username.enqueue(new Callback<UcenterModule>() {
                        @Override
                        public void onResponse(Call<UcenterModule> call, final Response<UcenterModule> response) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(IndividualActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFailure(Call<UcenterModule> call, Throwable t) {

                        }
                    });

                    userInfoDao.updateUserData(data.toString());
                }
            };

    @Override
    protected void onRestart() {
        super.onRestart();
        // TODO: 2017/1/16 此处状态会显现时可能出现bug，sp内临时值会一直存在
//        tvTitleFiv.setText(App.preferenceUtil.getString(PreferenceKey.TEMP_ADDRESS, null));

        inttInfoList();
    }
}
